<template>
  <div class="as-popconfirm"
       ref="asPopover"
       :class="['as-popconfirm--'+placement]">
    <transition name="as-fade">
      <div class="as-popconfirm__body"
           :style="style"
           v-show="visible">
        <div class="as-popconfirm__body_title">{{title}}</div>
        <div class="as-popconfirm__body_content">
          <as-button size="mini"
                     @click="cancel"
                     :type="cancelButtonType">{{cancelButtonText}}</as-button>
          <as-button size="mini"
                     @click="confirm"
                     :type="confirmButtonType">{{confirmButtonText}}</as-button>
        </div>
      </div>
    </transition>
    <div @click="clickPop">
      <slot></slot>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
  name: "AsPopconfirm",
  props: {
    placement: {
      type: String,
      default: "top"
    },
    title: {
      type: String,
      default: "这是一段内容确定删除吗？"
    },
    cancelButtonText: {
      type: String,
      default: "取消"
    },
    confirmButtonText: {
      type: String,
      default: "确认"
    },
    confirmButtonType: { type: String, default: "primary" },
    cancelButtonType: { type: String, default: "text" }
  },
  data() {
    return {
      visible: false,
      style: {},
      clickEvent: e => {
        if (this.$refs.asPopover && !this.$refs.asPopover.contains(e.target)) {
          this.visible = false;
        }
      }
    };
  },
  destroyed() {
    window.removeEventListener("click", this.clickEvent);
  },
  mounted() {
    let position, length;

    let { width, height } = this.$el.getBoundingClientRect();
    switch (this.placement) {
      case "top":
        position = "bottom";
        length = height + "px";
        break;
      case "bottom":
        position = "top";
        length = height + "px";
        break;
      case "left":
        position = "right";
        length = width + "px";
        break;
      case "right":
        position = "left";
        length = width + "px";
        break;
    }

    this.style = position + ":" + length;

    window.addEventListener("click", this.clickEvent);
  },
  methods: {
    clickPop() {
      this.visible = !this.visible;
    },
    cancel() {
      this.$emit("onCancel");
      this.visible = false;
    },
    confirm() {
      this.$emit("onConfirm");
      this.visible = false;
    }
  }
};
</script>
